<!-- 欠料分析 -->
<template>
  <el-dialog
    custom-class="underfeedAnalysisDialog"
    :fullscreen="true"
    append-to-body
    :close-on-click-modal="false"
    title="欠料分析"
    :visible.sync="underfeedAnalysisDialog.visible"
    v-if="underfeedAnalysisDialog.visible"
    @close="cancelUnderfeedData"
  >
    <el-steps :active="underfeedAnalysisDialog.active" align-center simple>
      <el-step title="欠料分析"></el-step>
      <el-step title="生成备料单"></el-step>
    </el-steps>
    <div class="underfeedAnalysisDialog-body" v-loading="dataLoading" :element-loading-text="loadingText" element-loading-spinner="el-icon-loading">
      <!-- 欠料分析 -->
      <el-row v-if="underfeedAnalysisDialog.active == 0" class="wireSide">
        <el-col :span="24">
          <el-tabs v-model="materialPrepareAnalysisTabs" type="border-card" style="margin: 10px 0">
            <el-tab-pane label="原材料发料欠料明细" name="first">
              <avue-crud
                :option="underfeedAnalysisDialog.rawMaterialWarehouse.option"
                :table-loading="underfeedAnalysisDialog.rawMaterialWarehouse.loading"
                :data="underfeedAnalysisDialog.rawMaterialWarehouse.data"
                v-model="underfeedAnalysisDialog.rawMaterialWarehouse.form"
                ref="rawMaterialWarehouseCrud"
              >
                <template slot="menuLeft">
                  <el-button icon="el-icon-s-tools" type="primary" size="small" @click.stop="handleOpenRuleDialog()">备料分析规则配置</el-button>
                  <el-button icon="el-icon-plus" type="primary" size="small" @click.stop="handleLinkLineSideWarehouseInventory()">线边仓库存查询</el-button>
                </template>
                <template slot-scope="{ row, index }" slot="qlfx">
                  <span v-if="row.completeAnalysis == 'SHORTAGE'" style="color: red">欠料</span>
                  <span v-else>齐料</span>
                </template>
                <template slot-scope="{ row, index }" slot="qlcl">
                  <span v-if="row.completeAnalysis == 'SHORTAGE'" style="color: red; cursor: pointer" @click="handleWaste(row, index)">处理</span>
                </template>
                <!-- 0=<应发数量<原材料可用数量 -->

                <template slot-scope="{ row, index }" slot="quantity">
                  <el-input-number
                    controls-position="right"
                    size="mini"
                    v-model="row.quantity"
                    :min="0"
                    :max="Number(row.materialQuantity)"
                    @change="(value) => changeQuantity(value, index, row)"
                  >
                  </el-input-number>
                </template>
              </avue-crud>
            </el-tab-pane>
            <el-tab-pane label="线边仓调拨欠料明细" name="second">
              <avue-crud
                :option="underfeedAnalysisDialog.wireSide.option"
                :table-loading="underfeedAnalysisDialog.wireSide.loading"
                :data="underfeedAnalysisDialog.wireSide.data"
                v-model="underfeedAnalysisDialog.wireSide.form"
                ref="addWireSideCrud"
              >
                <template slot="menuLeft">
                  <el-button icon="el-icon-s-tools" type="primary" size="small" @click.stop="handleOpenRuleDialog()">备料分析规则配置</el-button>
                  <el-button icon="el-icon-plus" type="primary" size="small" @click.stop="handleLinkLineSideWarehouseInventory()">线边仓库存查询</el-button>
                </template>
                <template slot-scope="{ row, index }" slot="qlfx">
                  <span v-if="row.completeAnalysis == 'SHORTAGE'" style="color: red">欠料</span>
                  <span v-else>齐料</span>
                </template>
                <!-- 线边仓裕量的绝对值 <= 应发数量 < 原材料库存数量-->
                <!-- :minRows="Math.abs(row.slackQuantity)"
                    :maxRows="row.materialQuantity" -->
                <!-- :min="Math.abs(row.slackQuantity)" -->
                <template slot-scope="{ row, index }" slot="quantity">
                  <el-input-number
                    controls-position="right"
                    size="mini"
                    :min="0"
                    :max="Number(row.materialQuantity)"
                    v-model="row.quantity"
                    @change="(value) => changeLineSideQuantity(value, row, index)"
                  ></el-input-number>
                </template>
                <template slot-scope="{ row, index }" slot="allocateToInventoryId">
                  <el-select
                    size="mini"
                    v-model="row.allocateToInventoryId"
                    @visible-change="(status) => visibleChange(status, row, index)"
                    @change="(value) => changeLineSide(value, row, index)"
                  >
                    <el-option v-for="item in lineSideDicData" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                  </el-select>
                </template>
              </avue-crud>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>

      <!-- 生成备料单 -->
      <el-row v-if="underfeedAnalysisDialog.active == 1" class="makePreMaterialList">
        <el-col :span="24">
          <el-tabs v-model="generateMaterialPreparationListTabs" type="border-card" style="margin: 10px 0">
            <el-tab-pane label="原材料发料明细" name="first">
              <avue-crud
                :option="underfeedAnalysisDialog.preMaterial.option"
                :table-loading="underfeedAnalysisDialog.preMaterial.loading"
                :data="underfeedAnalysisDialog.preMaterial.data"
                v-model="underfeedAnalysisDialog.preMaterial.form"
                ref="addWireSideCrud"
              >
                <template slot-scope="{ row }" slot="menu">
                  <el-button v-if="row.isShowPackBtn" type="text" icon="el-icon-view" size="small" plain style="border: 0 !important" @click.stop="handlePackView(row)"
                    >包装详情</el-button
                  >
                </template>
                <template slot-scope="{ row }" slot="recommendLotNo">
                  <span style="color: #409eff; cursor: pointer" @click="handleLotNoView(row)"> {{ row.recommendLotNo }}</span>
                </template>
              </avue-crud>
            </el-tab-pane>
            <el-tab-pane label="线边仓调拨明细" name="second">
              <avue-crud
                :option="underfeedAnalysisDialog.lineSideWareHouseTransferDetails.option"
                :table-loading="underfeedAnalysisDialog.lineSideWareHouseTransferDetails.loading"
                :data="underfeedAnalysisDialog.lineSideWareHouseTransferDetails.data"
                v-model="underfeedAnalysisDialog.lineSideWareHouseTransferDetails.form"
                ref="lineSideWareHouseTransferDetailsCrud"
              >
                <template slot-scope="{ row }" slot="menu">
                  <el-button v-if="row.isShowPackBtn" type="text" icon="el-icon-view" size="small" plain style="border: 0 !important" @click.stop="handlePackView(row)"
                    >包装详情</el-button
                  >
                </template>
                <template slot-scope="{ row, index }" slot="qlfx">
                  <span v-if="row.completeAnalysis == 'SHORTAGE'" style="color: red">欠料</span>
                  <span v-else>齐料</span>
                </template>
                <template slot-scope="{ row }" slot="recommendLotNo">
                  <span style="color: #409eff; cursor: pointer" @click="handleLotNoView(row)"> {{ row.recommendLotNo }}</span>
                </template>
              </avue-crud>
            </el-tab-pane>
            <el-tab-pane label="智能料架原材料发料明细" name="third"> </el-tab-pane>
            <el-tab-pane label="原材料发料欠料明细" name="fourth">
              <avue-crud
                :option="underfeedAnalysisDialog.rawMaterialWarehouseShortageDetails.option"
                :table-loading="underfeedAnalysisDialog.rawMaterialWarehouseShortageDetails.loading"
                :data="underfeedAnalysisDialog.rawMaterialWarehouseShortageDetails.data"
                v-model="underfeedAnalysisDialog.rawMaterialWarehouseShortageDetails.form"
                ref="rawMaterialWarehouseShortageDetailsCrud"
              >
              </avue-crud>
            </el-tab-pane>
            <el-tab-pane label="线边仓调拨欠料明细" name="fifth">
              <avue-crud
                :option="underfeedAnalysisDialog.lineSideWareHouseTransfershortageDetails.option"
                :table-loading="underfeedAnalysisDialog.lineSideWareHouseTransfershortageDetails.loading"
                :data="underfeedAnalysisDialog.lineSideWareHouseTransfershortageDetails.data"
                v-model="underfeedAnalysisDialog.lineSideWareHouseTransfershortageDetails.form"
                ref="lineSideWareHouseTransfershortageDetailsCrud"
              >
              </avue-crud>
            </el-tab-pane>
            <el-tab-pane label="普通货架拆包明细" name="sixth">
              <avue-crud
                :option="underfeedAnalysisDialog.unpackingDetails.option"
                :table-loading="underfeedAnalysisDialog.unpackingDetails.loading"
                :data="underfeedAnalysisDialog.unpackingDetails.data"
                v-model="underfeedAnalysisDialog.unpackingDetails.form"
                ref="unpackingDetailsCrud"
              >
              </avue-crud>
            </el-tab-pane>
            <el-tab-pane label="智能料架拆包明细" name="seventh"> </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>

    <div slot="footer" class="dialog-footer">
      <!-- <el-button v-preventReClick type="primary" size="small" @click="saveAddCache" icon="el-icon-circle-plus-outline">保存草稿</el-button> -->
      <!-- <el-button type="primary" size="small" @click="handlePreStep" icon="el-icon-back" v-if="underfeedAnalysisDialog.active != 0">上一步</el-button> -->
      <el-button v-preventReClick type="primary" size="small" @click="handleNextStep" icon="el-icon-right" v-if="underfeedAnalysisDialog.active == 0">下一步</el-button>
      <el-button v-preventReClick @click="submitAddData" type="primary" size="small" icon="el-icon-circle-plus-outline" v-if="underfeedAnalysisDialog.active == 1"
        >提 交</el-button
      >
      <el-button @click="cancelUnderfeedData" size="small" icon="el-icon-circle-close">取 消</el-button>
    </div>
    <!-- 备料推荐包装详情 -->
    <packBoxDialog ref="packBox" :visible="packBoxDialog.visible" @closeDialog="packBoxDialog.visible = false"></packBoxDialog>
    <!-- 备料推荐批次详情 -->
    <lotNoDialog ref="lotNoBox" :visible="lotNoDialog.visible" @closeDialog="lotNoDialog.visible = false"></lotNoDialog>
    <!-- 欠料处理弹窗 -->
    <handleWasteDialog ref="handleWasteBox" :visible="handleWasteDialog.visible" @closeHandleDialog="closeHandleDialog"></handleWasteDialog>
  </el-dialog>
</template>

<script>
import {
  submitRule,
  searchRule,
  getList,
  getMaterialList,
  getDetail,
  flowExecute,
  unfeedAnalysis,
  getAnalysisForLineSide,
  getAnalysisListForLineSide,
  singleRowPrepareAnalysis
} from '@/api/warehouse/preMaterialList';
import { getList as getPreList } from '@/api/warehouse/sheetheader';
import packBoxDialog from './packBoxDialog.vue';
import lotNoDialog from './lotNoDialog.vue';
import handleWasteDialog from './handleWasteDialog.vue';
export default {
  name: 'underfeedAnalysisDialog',
  components: { packBoxDialog, lotNoDialog, handleWasteDialog },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      rowId: null,
      materialPrepareAnalysisTabs: 'first',
      generateMaterialPreparationListTabs: 'first',
      lineSideDicData: [], //线边仓列表
      dataLoading: false,
      loadingText: '',
      isFifo: false,
      specifyMaterialCategoryAnalysisList: [],
      specifyMaterialCategoryCodes: [],
      isSpecifyAnalysis: false,
      splitRule: null,
      rowData: null,
      prepareMaterialSheetHeaderId: '',
      originSheetIdList: null,
      sheetHeader: null,
      sheetDetailList: null,
      materialRollingList: [],
      allocateRequirementList: [],
      prepareMaterialSheet: null,
      underfeedAnalysisDialog: {
        title: '欠料分析',
        visible: false,
        active: 0,
        sheetHeader: {},
        // 原材料发料欠料明细
        rawMaterialWarehouse: {
          loading: false,
          option: {
            calcHeight: 30,
            height: '450px',
            tip: false,
            searchShow: true,
            searchMenuPosition: 'right',
            dialogClickModal: false,
            searchLabelWidth: 80,
            border: true,
            page: false,
            viewBtn: false,
            addBtn: false,
            selection: false,
            printBtn: false,
            editBtn: false,
            delBtn: false,
            index: true,
            indexLabel: '序号',
            searchMenuSpan: 16,
            columnBtn: false,
            searchBtnText: '查 询',
            refreshBtn: false,
            menu: false,
            highlightCurrentRow: true,
            defaultSort: {
              prop: 'partNo',
              order: 'descending'
            },
            column: [
              { sortable: true, label: '物料编码', prop: 'partNo' },
              {
                label: '物料名称',
                prop: 'partName'
              },
              {
                label: '单位',
                prop: 'uom'
              },
              {
                label: '需求数量',
                prop: 'originalQtyTotal'
              },
              {
                label: '已备数量',
                prop: 'oldQuantity'
              },
              {
                label: '欠发数量',
                prop: 'originalShortageQuantity'
              },
              {
                label: '原材料可用库存',
                prop: 'materialQuantity'
              },
              {
                label: '最小包规数量',
                prop: 'mpq'
              },
              {
                label: '拆包形式',
                prop: 'unpackingForm',
                width: 80
              },
              {
                label: '齐料分析',
                prop: 'qlfx',
                width: 80
              },
              {
                label: '欠料处理',
                prop: 'qlcl',
                width: 80
              },
              {
                label: '应发数量',
                prop: 'quantity',
                width: 180
              },
              {
                label: '超发数量',
                prop: 'overshipmentQuantity'
              },
              {
                label: '欠料数量',
                prop: 'shortageQuantity'
              }
            ]
          },
          form: {},
          data: [
            // {
            //   materialQuantity: 10,
            //   qfsl: 20,
            //   completeAnalysis: 'SHORTAGE'
            // }
          ]
        },
        // 线边仓调拨欠料明细
        wireSide: {
          loading: false,
          option: {
            calcHeight: 30,
            height: '450px',
            tip: false,
            searchShow: true,
            searchMenuPosition: 'right',
            dialogClickModal: false,
            searchLabelWidth: 80,
            border: true,
            page: false,
            viewBtn: false,
            addBtn: false,
            selection: false,
            printBtn: false,
            editBtn: false,
            delBtn: false,
            index: true,
            indexLabel: '序号',
            searchMenuSpan: 16,
            columnBtn: false,
            searchBtnText: '查 询',
            refreshBtn: false,
            menu: false,
            highlightCurrentRow: true,
            defaultSort: {
              prop: 'partNo',
              order: 'descending'
            },
            column: [
              { sortable: true, label: '物料编码', prop: 'partNo' },
              {
                label: '物料名称',
                prop: 'partName'
              },
              {
                label: '单位',
                prop: 'uom'
              },
              {
                label: '需求数量',
                prop: 'originalQtyTotal'
              },
              {
                label: '原材料可用库存',
                prop: 'materialQuantity'
              },
              {
                label: '拆包形式',
                prop: 'unpackingForm',
                width: 80
              },
              {
                label: '线边仓',
                prop: 'allocateToInventoryName'
              },
              {
                label: '欠发数量',
                prop: 'originalShortageQuantity'
              },
              {
                label: '线边仓可用数量',
                prop: 'lineSideQuantity'
              },
              {
                label: '最小包规数量',
                prop: 'mpq'
              },
              {
                label: '线边仓裕量',
                prop: 'slackQuantity'
              },
              {
                label: '齐料分析',
                prop: 'qlfx',
                width: 80
              },
              {
                label: '应发数量',
                prop: 'quantity',
                width: 180
              },
              {
                label: '欠料数量',
                prop: 'shortageQuantity'
              }
            ]
          },
          form: {},
          data: []
        },
        // 生成备料单
        // 1.原材料发料明细
        preMaterial: {
          loading: false,
          option: {
            calcHeight: 30,
            height: '450px',
            tip: false,
            searchShow: true,
            searchMenuPosition: 'right',
            dialogClickModal: false,
            searchLabelWidth: 80,
            border: true,
            viewBtn: false,
            addBtn: false,
            selection: false,
            page: false,
            printBtn: false,
            editBtn: false,
            delBtn: false,
            index: true,
            indexLabel: '序号',
            searchMenuSpan: 16,
            columnBtn: false,
            searchBtnText: '查 询',
            refreshBtn: false,
            menu: true,
            menuTitle: '推荐包装',
            menuWidth: 100,
            defaultSort: {
              prop: 'partNo',
              order: 'descending'
            },
            column: [
              {
                sortable: true,
                label: '物料编码',
                prop: 'partNo'
              },
              {
                label: '物料名称',
                prop: 'partName'
              },
              {
                label: '单位',
                prop: 'uom'
              },
              {
                label: '需求数量',
                prop: 'originalQtyTotal'
              },
              {
                label: '最小包规数量',
                prop: 'mpq'
              },
              {
                label: '应发数量',
                prop: 'quantity'
              },
              {
                label: '超发数量',
                prop: 'overshipmentQuantity'
              },
              {
                label: '欠料数量',
                prop: 'shortageQuantity'
              },
              {
                label: '推荐仓库',
                prop: 'recommendInventoryCode',
                overHidden: true
              },
              {
                label: '推荐储位',
                prop: 'recommendAreaCode',
                overHidden: true
              },
              {
                label: '推荐批次',
                prop: 'recommendLotNo',
                overHidden: true
              }
            ]
          },
          form: {},
          data: []
        },
        // 2.线边仓调拨明细
        lineSideWareHouseTransferDetails: {
          loading: false,
          option: {
            calcHeight: 30,
            height: '450px',
            tip: false,
            searchShow: true,
            searchMenuPosition: 'right',
            dialogClickModal: false,
            searchLabelWidth: 80,
            border: true,
            viewBtn: false,
            addBtn: false,
            selection: false,
            page: false,
            printBtn: false,
            editBtn: false,
            delBtn: false,
            index: true,
            indexLabel: '序号',
            searchMenuSpan: 16,
            columnBtn: false,
            searchBtnText: '查 询',
            refreshBtn: false,
            menu: false,
            defaultSort: {
              prop: 'partNo',
              order: 'descending'
            },
            // menuTitle: '推荐包装',
            // menuWidth: 100,
            column: [
              { sortable: true, label: '物料编码', prop: 'partNo' },
              {
                label: '物料名称',
                prop: 'partName'
              },
              {
                label: '单位',
                prop: 'uom'
              },
              {
                label: '需求数量',
                prop: 'originalQtyTotal'
              },
              {
                label: '拆包形式',
                prop: 'unpackingForm'
              },
              {
                label: '最小包规数量',
                prop: 'mpq'
              },
              {
                label: '原材料可用库存',
                prop: 'materialQuantity'
              },
              {
                label: '线边仓',
                prop: 'allocateToInventoryName'
              },
              {
                label: '线边仓可用数量',
                prop: 'lineSideQuantity'
              },
              {
                label: '线边仓裕量',
                prop: 'slackQuantity'
              },
              {
                label: '齐料分析',
                prop: 'qlfx',
                width: 80
              },
              {
                label: '应发数量',
                prop: 'quantity'
              },
              {
                label: '欠料数量',
                prop: 'shortageQuantity'
              }
            ]
          },
          form: {},
          data: []
        },
        // 3.原材料仓欠料明细
        rawMaterialWarehouseShortageDetails: {
          loading: false,
          option: {
            calcHeight: 30,
            height: '450px',
            tip: false,
            searchShow: true,
            searchMenuPosition: 'right',
            dialogClickModal: false,
            searchLabelWidth: 80,
            border: true,
            viewBtn: false,
            addBtn: false,
            selection: false,
            page: false,
            printBtn: false,
            editBtn: false,
            delBtn: false,
            index: true,
            indexLabel: '序号',
            searchMenuSpan: 16,
            columnBtn: false,
            searchBtnText: '查 询',
            refreshBtn: false,
            menu: false,
            defaultSort: {
              prop: 'partNo',
              order: 'descending'
            },
            column: [
              { sortable: true, label: '物料编码', prop: 'partNo' },
              {
                label: '物料名称',
                prop: 'partName'
              },
              {
                label: '单位',
                prop: 'uom'
              },
              {
                label: '需求数量',
                prop: 'originalQtyTotal'
              },
              {
                label: '最小包规数量',
                prop: 'mpq'
              },
              {
                label: '应发数量',
                prop: 'quantity'
              },
              {
                label: '欠料数量',
                prop: 'shortageQuantity'
              }
            ]
          },
          form: {},
          data: []
        },
        // 4.线边仓调拨欠料明细
        lineSideWareHouseTransfershortageDetails: {
          loading: false,
          option: {
            calcHeight: 30,
            height: '450px',
            tip: false,
            searchShow: true,
            searchMenuPosition: 'right',
            dialogClickModal: false,
            searchLabelWidth: 80,
            border: true,
            viewBtn: false,
            addBtn: false,
            selection: false,
            page: false,
            printBtn: false,
            editBtn: false,
            delBtn: false,
            index: true,
            indexLabel: '序号',
            searchMenuSpan: 16,
            columnBtn: false,
            searchBtnText: '查 询',
            refreshBtn: false,
            menu: false,
            defaultSort: {
              prop: 'partNo',
              order: 'descending'
            },
            column: [
              { sortable: true, label: '物料编码', prop: 'partNo' },
              {
                label: '物料名称',
                prop: 'partName'
              },
              {
                label: '单位',
                prop: 'uom'
              },
              {
                label: '需求数量',
                prop: 'originalQtyTotal'
              },
              {
                label: '最小包规数量',
                prop: 'mpq'
              },
              {
                label: '线边仓',
                prop: 'allocateToInventoryName'
              },
              {
                label: '应发数量',
                prop: 'quantity'
              },
              {
                label: '欠料数量',
                prop: 'shortageQuantity'
              }
            ]
          },
          form: {},
          data: []
        },
        // 5.拆包明细
        unpackingDetails: {
          loading: false,
          option: {
            calcHeight: 30,
            height: '450px',
            tip: false,
            searchShow: true,
            searchMenuPosition: 'right',
            dialogClickModal: false,
            searchLabelWidth: 80,
            border: true,
            viewBtn: false,
            addBtn: false,
            selection: false,
            page: false,
            printBtn: false,
            editBtn: false,
            delBtn: false,
            index: true,
            indexLabel: '序号',
            searchMenuSpan: 16,
            columnBtn: false,
            searchBtnText: '查 询',
            refreshBtn: false,
            menu: false,
            defaultSort: {
              prop: 'partNo',
              order: 'descending'
            },
            column: [
              { sortable: true, label: '物料编码', prop: 'partNo' },
              {
                label: '物料名称',
                prop: 'partName'
              },
              {
                label: '单位',
                prop: 'uom'
              },
              {
                label: '需求数量',
                prop: 'originalQtyTotal'
              },
              {
                label: '推荐批次',
                prop: 'recommendLotNo'
              },
              {
                label: '备料分析层级',
                prop: 'blcjfx'
              },
              {
                label: '待拆包装条码',
                prop: 'dcbztm'
              },
              {
                label: '包装数量',
                prop: 'bzquantity'
              },
              {
                label: '需拆出数量',
                prop: 'unpackQuantity'
              }
            ]
          },
          form: {},
          data: []
        }
      },
      packBoxDialog: {
        visible: false
      },
      lotNoDialog: {
        visible: false
      },
      handleWasteDialog: {
        visible: false
      }
    };
  },
  watch: {
    visible: {
      handler(value) {
        this.underfeedAnalysisDialog.active = 0;
        this.underfeedAnalysisDialog.visible = value;
      }
    },
    'preMaterialRuleDialog.form.splitType': {
      handler(value) {
        if (value == 'PEOPLE') {
          this.preMaterialRuleDialog.form.cangkuValue = '';
        } else if (value == 'WAREHOUSE') {
          this.preMaterialRuleDialog.form.renyuanValue = '';
        } else {
          this.preMaterialRuleDialog.form.cangkuValue = '';
          this.preMaterialRuleDialog.form.renyuanValue = '';
        }
      },
      deep: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {},
  methods: {
    onLoad(page, params = {}) {
      this.underfeedAnalysisDialog.merge.productList.loading = true;
      params.sheetTypeStrList = 'IMO,RO,ROB'; //用料清单;领料单;补料单
      params.status = 1; //用料清单;领料单;补料单
      getPreList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.underfeedAnalysisDialog.merge.productList.page.total = data.total;
        this.underfeedAnalysisDialog.merge.productList.data = data.records;
        this.underfeedAnalysisDialog.merge.productList.loading = false;
        this.selectionClear();
      });
    },
    handleOpenRuleDialog() {
      this.$emit('openRuleDialog', 'underfeed', {
        isFifo: this.isFifo,
        isSpecifyAnalysis: this.isSpecifyAnalysis,
        specifyMaterialCategoryCodes: this.specifyMaterialCategoryCodes,
        specifyMaterialCategoryAnalysisList: this.specifyMaterialCategoryAnalysisList
      });
    },
    handleAdd() {
      this.underfeedAnalysisDialog.active = 0;
      this.underfeedAnalysisDialog.visible = true;
    },
    getLineSideData() {
      getMaterialList({
        inventoryType: 'LINE_SIDE'
      })
        .then((res) => {
          let data = res.data.data;
          this.lineSideDicData = data.map((d) => {
            return {
              label: d.name,
              inventoryCode: d.code,
              value: d.id
            };
          });
        })
        .catch((err) => {});
    },
    // 备料规则配置保存分析
    saveAnalysis() {
      const that = this;
      that
        .$confirm('点保存后，当前页面的数据会重新分析，请慎重！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.loadingText = '分析中，请稍后';
          that.dataLoading = true;
          let params = {
            actCode: 'material-shortage-activity',
            requestParams: {
              type: 'PREPARE_MATERIAL_SHEET_ANALYSIS_EDIT_SUBMIT',
              preparationAnalysisRule: {
                isFifo: that.isFifo,
                specifyMaterialCategoryAnalysisList: that.specifyMaterialCategoryAnalysisList
              },
              prepareMaterialSheetHeaderId: that.rowId,
              underMaterialAnalysis: true
            }
          };
          return params;
        })
        .then((params) => {
          unfeedAnalysis(params).then((res) => {
            let data = res.data.data;
            let prepareMaterialSheetAnalysisResult = data.prepareMaterialSheetAnalysisResult;
            that.underfeedAnalysisDialog.rawMaterialWarehouse.data = prepareMaterialSheetAnalysisResult.sheetDetailForNormal;
            that.underfeedAnalysisDialog.wireSide.data = prepareMaterialSheetAnalysisResult.sheetDetailListForFlush;
            that.underfeedAnalysisDialog.sheetHeader = prepareMaterialSheetAnalysisResult.sheetHeader;
          });
        })
        .catch(() => {})
        .finally(() => {
          that.dataLoading = false;
        });
    },
    handleParams() {
      const that = this;
      switch (that.underfeedAnalysisDialog.active) {
        case 0:
          return {
            actCode: 'preview-recommend-act',
            requestParams: {
              type: 'PREPARE_MATERIAL_SHEET_ANALYSIS',
              preparationAnalysisRule: {
                isFifo: that.isFifo,
                specifyMaterialCategoryAnalysisList: that.specifyMaterialCategoryAnalysisList
              },
              prepareMaterialSheet: {
                sheetHeader: that.underfeedAnalysisDialog.sheetHeader,
                sheetDetailForNormal: that.underfeedAnalysisDialog.rawMaterialWarehouse.data,
                sheetDetailListForFlush: that.underfeedAnalysisDialog.wireSide.data
              }
            }
          };
        case 1:
          return {
            actCode: 'shortage-analysis-submit-act',
            requestParams: {
              type: 'PREPARE_MATERIAL_SHEET_FULL_SUBMIT',
              preparationAnalysisRule: {
                isFifo: that.isFifo,
                specifyMaterialCategoryAnalysisList: that.specifyMaterialCategoryAnalysisList
              },
              prepareMaterialSheet: that.prepareMaterialSheet,
              materialRollingList: that.materialRollingList,
              allocateRequirementList: that.allocateRequirementList
              // prepareMaterialSheetHeaderId: that.prepareMaterialSheetHeaderId //备料单id
            }
          };
        default:
          break;
      }
    },
    // 保存草稿
    saveAddCache() {
      if (this.underfeedAnalysisDialog.active === 0) {
        if (this.underfeedAnalysisDialog.merge.selectedList.data.length == 0) {
          this.$message.warning('右侧已选中列表数据为空，请先操作');
          return false;
        }
        let params = this.handleParams();
        this.dataLoading = true;
        this.loadingText = '合并备料单中，请稍后';
        // 合并备料单
        flowExecute(params)
          .then((res) => {
            let data = res.data.data;
            this.prepareMaterialSheetHeaderId = data.prepareMaterialSheetVo.sheetHeader.id;
            this.originSheetIdList = data.prepareMaterialSheetVo.originSheetIdList;
            this.sheetHeader = data.prepareMaterialSheetVo.sheetHeader;
            this.sheetDetailList = data.prepareMaterialSheetVo.sheetDetailList;
            this.underfeedAnalysisDialog.wireSide.data = data.prepareMaterialSheetVo.sheetDetailListForFlush;
          })
          .catch(() => {})
          .finally(() => {
            this.dataLoading = false;
          });
      }
      if (this.underfeedAnalysisDialog.active === 1) {
        // 无线边仓调拨物料，直接点下一步即可
        if (this.underfeedAnalysisDialog.wireSide.data.length == 0) {
          // this.underfeedAnalysisDialog.preMaterial.data = this.underfeedAnalysisDialog.wireSide.data;
        } else {
          // 是否存在没有选择线边仓和应发数量的数据
          let emptyData = this.underfeedAnalysisDialog.wireSide.data.find((d) => !d.allocateToInventoryId);
          if (emptyData) {
            this.$message.warning('线边仓分析数据中心存在没选择线边仓，请仔细检查后点击下一步');
            return false;
          }
        }
        let params = this.handleParams();
        this.dataLoading = true;
        this.loadingText = '线边仓分析中，请稍后';
        // 线边仓分析
        flowExecute(params)
          .then((res) => {
            let data = res.data.data;
            this.prepareMaterialSheetHeaderId = data.prepareMaterialSheetVo.sheetHeader.id;
            this.underfeedAnalysisDialog.preMaterial.data = data.prepareMaterialSheetVo.sheetDetailList;
            console.log('data', data);
          })
          .catch(() => {})
          .finally(() => {
            this.dataLoading = false;
          });
      }
    },
    // 下一步
    handleNextStep() {
      if (this.underfeedAnalysisDialog.active === 0) {
        let params = this.handleParams();
        this.dataLoading = true;
        this.loadingText = '欠料分析中，请稍后';
        console.log('params', params);
        // 欠料分析
        flowExecute(params)
          .then((res) => {
            let data = res.data.data;
            this.underfeedAnalysisDialog.active++;
            this.generateMaterialPreparationListTabs = 'first';

            this.materialRollingList = data.materialRollingList;
            this.allocateRequirementList = data.allocateRequirementList;
            this.prepareMaterialSheet = data.prepareMaterialSheetVo;

            this.prepareMaterialSheetHeaderId = data.prepareMaterialSheetVo.sheetHeader.id;
            // 原材料发料明细
            data.prepareMaterialSheetVo.sheetDetailForNormal.forEach((item) => {
              if (item.sheetRecommendList.length > 0) {
                let recommendInventoryCode = item.sheetRecommendList.map((list) => list.recommendDataDTO && list.recommendDataDTO.recommendInventoryCode);
                let recommendAreaCode = item.sheetRecommendList.map((list) => list.recommendDataDTO && list.recommendDataDTO.recommendAreaCode);
                let recommendLotNo = item.sheetRecommendList.map((list) => {
                  if (list.recommendDataDTO && list.recommendDataDTO.recommendLotNo) {
                    return list.recommendDataDTO.recommendLotNo + '(' + list.recommendDataDTO.recommendLotQuantity + ')';
                  }
                });
                item.recommendInventoryCode = [...new Set(recommendInventoryCode)].join(',');
                item.recommendAreaCode = [...new Set(recommendAreaCode)].join(',');
                // item.recommendLotNo = [...new Set(recommendLotNo)].join(',');
                item.recommendLotNo = recommendLotNo.join(',');
                item.isShowPackBtn = recommendLotNo.length == 0;
              } else {
                item.recommendInventoryCode = '';
                item.recommendAreaCode = '';
                item.recommendLotNo = '';
                item.isShowPackBtn = false;
              }
            });
            this.underfeedAnalysisDialog.preMaterial.data = data.prepareMaterialSheetVo.sheetDetailForNormal;
            // 线边仓调拨明细
            data.prepareMaterialSheetVo.sheetDetailListForFlush.forEach((item) => {
              if (item.sheetRecommendList.length > 0) {
                let recommendInventoryCode = item.sheetRecommendList.map((list) => list.recommendDataDTO && list.recommendDataDTO.recommendInventoryCode);
                let recommendAreaCode = item.sheetRecommendList.map((list) => list.recommendDataDTO && list.recommendDataDTO.recommendAreaCode);
                let recommendLotNo = item.sheetRecommendList.map((list) => {
                  if (list.recommendDataDTO && list.recommendDataDTO.recommendLotNo) {
                    return list.recommendDataDTO.recommendLotNo + '(' + list.recommendDataDTO.recommendLotQuantity + ')';
                  }
                });
                item.recommendInventoryCode = [...new Set(recommendInventoryCode)].join(',');
                item.recommendAreaCode = [...new Set(recommendAreaCode)].join(',');
                // item.recommendLotNo = [...new Set(recommendLotNo)].join(',');
                item.recommendLotNo = recommendLotNo.join(',');
                item.isShowPackBtn = recommendLotNo.length == 0;
              } else {
                item.recommendInventoryCode = '';
                item.recommendAreaCode = '';
                item.recommendLotNo = '';
                item.isShowPackBtn = false;
              }
            });
            this.underfeedAnalysisDialog.lineSideWareHouseTransferDetails.data = data.prepareMaterialSheetVo.sheetDetailListForFlush;
            // 原材料发料欠料明细
            this.underfeedAnalysisDialog.rawMaterialWarehouseShortageDetails.data = this.underfeedAnalysisDialog.preMaterial.data.filter((d) => Number(d.shortageQuantity) > 0);
            // 线边仓调拨欠料明细
            this.underfeedAnalysisDialog.lineSideWareHouseTransfershortageDetails.data = this.underfeedAnalysisDialog.lineSideWareHouseTransferDetails.data.filter(
              (d) => Number(d.shortageQuantity) > 0
            );
          })
          .catch(() => {})
          .finally(() => {
            this.dataLoading = false;
          });
      }
    },
    // 上一步
    handlePreStep() {
      this.underfeedAnalysisDialog.active--;
      this.materialPrepareAnalysisTabs = 'first';
    },
    // 生成备料单
    submitAddData() {
      this.dataLoading = true;
      this.loadingText = '生产备料单中，请稍后';
      let params = this.handleParams();
      console.log('params', params);
      flowExecute(params)
        .then((res) => {
          let data = res.data.data;
          this.underfeedAnalysisDialog.visible = false;
          this.$emit('unfeedGenerateSuccess');
          console.log('data', data);
        })
        .catch(() => {})
        .finally(() => {
          this.dataLoading = false;
        });
    },
    cancelUnderfeedData() {
      this.underfeedAnalysisDialog.visible = false;
      // this.underfeedAnalysisDialog.merge.selectedList.data = [];
      // this.underfeedAnalysisDialog.merge.productList.page.currentPage = 1;
      // this.underfeedAnalysisDialog.merge.productList.page.curresizentPage = 15;
      this.$emit('closeDialog');
    },
    handleLinkLineSideWarehouseInventory() {
      // this.cancelUnderfeedData();
      const params = {};
      let routeData = this.$router.resolve({
        path: '/warehouse/productrefactor/lineSideWarehouseInventory'
      });
      window.open(routeData.href, '_blank');
      // this.$router.push({ path: '/warehouse/productrefactor/lineSideWarehouseInventory' });
    },
    handleCurrentRowChange(value) {
      this.rowData = structuredClone(value);
    },
    addMergeProductCurrentChange(currentPage) {
      this.underfeedAnalysisDialog.preMaterial.page.currentPage = currentPage;
    },
    addMergeProductSizeChange(pageSize) {
      this.underfeedAnalysisDialog.preMaterial.page.pageSize = pageSize;
    },
    visibleChange(status, row, index) {
      if (status) {
        this.getLineSideData();
      }
    },
    changeLineSide(value, row, index) {
      let find = this.lineSideDicData.find((d) => d.value == value);
      if (find) {
        this.underfeedAnalysisDialog.wireSide.data[index].allocateToInventoryId = find.value;
        this.underfeedAnalysisDialog.wireSide.data[index].allocateToInventoryCode = find.inventoryCode;
        this.underfeedAnalysisDialog.wireSide.data[index].allocateToInventoryName = find.label;
        // this.underfeedAnalysisDialog.wireSide.data[index].toInventoryQuantity = find.quantity;
        // this.underfeedAnalysisDialog.wireSide.data[index].slackQuantity = find.quantity - row.originalQtyTotal;
        row.allocateToInventoryCode = find.inventoryCode;
        row.allocateToInventoryId = find.value;
        if (this.rowData === null) {
          this.rowData = {};
        }
        this.$set(this.rowData, 'allocateToInventoryId', find.value);
        this.$set(this.rowData, 'allocateToInventoryCode', find.inventoryCode);
        this.$set(this.rowData, 'allocateToInventoryName', find.label);
      }
      console.log('row', row, this.rowData);
      getAnalysisForLineSide(row)
        .then((res) => {
          let data = res.data.data;
          this.underfeedAnalysisDialog.wireSide.data[index].lineSideQuantity = data.lineSideQuantity;
          this.underfeedAnalysisDialog.wireSide.data[index].slackQuantity = data.slackQuantity;
        })
        .catch((err) => {});
    },
    // 推荐包装详情
    handlePackView(row) {
      this.packBoxDialog.visible = true;
      let data = [];
      row.sheetRecommendList.forEach((list) => {
        if (list.recommendDataDTO.recommendPacks && list.recommendDataDTO.recommendPacks.length > 0) {
          list.recommendDataDTO.recommendPacks.forEach((pItem) => {
            pItem.recommendInventoryCode = list.recommendDataDTO.recommendInventoryCode;
            pItem.recommendAreaCode = list.recommendDataDTO.recommendAreaCode;
            pItem.recommendLotNo = list.recommendDataDTO.recommendLotNo;
            data.push(pItem);
          });
        }
      });
      this.$refs.packBox.packBoxDialog.data = data;
    },
    // 推荐批次详情
    handleLotNoView(row) {
      this.lotNoDialog.visible = true;
      row.sheetRecommendList.forEach((list) => {
        list.recommendLotQuantity = list.recommendDataDTO.recommendLotQuantity;
      });
      this.$refs.lotNoBox.lotNoDialog.data = structuredClone(row.sheetRecommendList);
      this.$refs.lotNoBox.setFormHeader(row);
    },
    // 欠料处理
    handleWaste(row, index) {
      this.handleWasteDialog.visible = true;
      this.$refs.handleWasteBox.handleWasteForm = row;
      this.$refs.handleWasteBox.getData(row.partNo, index);
    },
    closeHandleDialog(data, index) {
      console.log('data', data, index);
      this.handleWasteDialog.visible = false;
      if (data) {
        this.underfeedAnalysisDialog.rawMaterialWarehouse.data.splice(index, 1, data);
      }
    },
    changeQuantity(value, index, row) {
      singleRowPrepareAnalysis(row)
        .then((res) => {
          let data = res.data.data;
          let findIndex = this.underfeedAnalysisDialog.rawMaterialWarehouse.data.findIndex((item) => {
            return item.id == row.id;
          });
          console.log(findIndex, 'findIndex');
          this.underfeedAnalysisDialog.rawMaterialWarehouse.data.splice(findIndex, 1, data);
        })
        .catch((err) => {});
    },
    // 改变线边仓应发数量
    changeLineSideQuantity(value, row, index) {
      row.preparationAnalysisRuleDto = {
        isFifo: this.isFifo,
        specifyMaterialCategoryAnalysisList: this.specifyMaterialCategoryAnalysisList
      };
      singleRowPrepareAnalysis(row)
        .then((res) => {
          let data = res.data.data;
          let findIndex = this.underfeedAnalysisDialog.wireSide.data.findIndex((item) => {
            return item.id == row.id;
          });
          this.underfeedAnalysisDialog.wireSide.data.splice(findIndex, 1, data);
        })
        .catch((err) => {});
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .underfeedAnalysisDialog .merge,
::v-deep .underfeedAnalysisDialog .makePreMaterialList {
  .avue-crud__menu {
    display: none;
  }
  .ruleRowForm {
    margin-bottom: 5px;
    .el-radio {
      margin-right: 10px;
    }
    .header-icon {
      margin-right: 10px;
    }
  }
}
::v-deep .underfeedAnalysisDialog {
  &-body {
    margin-top: 10px;
    .el-transfer-button {
      position: absolute;
      left: 50%;
      top: 50%;
      z-index: 100;
      transform: translate(-50%, -50%);
      margin: 0;
      .btn {
        background-color: #409eff;
        color: #fff;
        &.is-disabled {
          background-color: #fff !important;
          color: #ccc !important;
        }
      }
    }
  }
}
</style>
